﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GameView.Comment;
using GameView.Services.Comment;
using GameView.Views;
using System.Collections.ObjectModel;

namespace GameView.ViewModels
{
    public partial class ProjectViewModel : ObservableObject
    {
        private readonly ProjectService _service;

        public ProjectViewModel(ProjectService service)
        {
            _service = service;
            LoadData().ConfigureAwait(false);
        }

        [ObservableProperty]
        private string _newProjectName = string.Empty;

        [ObservableProperty]
        private string _newGameName = string.Empty;

        [ObservableProperty]
        private bool _addP = false;

        [ObservableProperty]
        private bool _addG = false;

        [ObservableProperty]
        private bool _delTN = false;

        [ObservableProperty]
        private ObservableCollection<TreeNode> _nodes = new();

        [ObservableProperty]
        private bool _isLoading = false;

#nullable enable

        [ObservableProperty]
        [NotifyCanExecuteChangedFor(nameof(ShowAddGameDialogCommand))]
        [NotifyCanExecuteChangedFor(nameof(RemoveNodeCommand))]
        private TreeNode? _selectedNode;

        [RelayCommand]
        private void SelectedItemChanged(object selectedItem)
        {
            // 设置新选中的项
            if (selectedItem is TreeNode newNode)
            {
                //newNode.IsSelected = true;
                SelectedNode = newNode;
            }
            else
            {
                SelectedNode = null;
            }
        }

        [RelayCommand]
        private async Task RefreshList()
        {
            await LoadData();
        }

        private bool CanAddGame() => SelectedNode != null && SelectedNode.Type == 0;

        [RelayCommand(CanExecute = nameof(CanRemove))]
        private async Task RemoveNode()
        {
            await Task.CompletedTask;
            DelTN = true;
        }

        private bool CanRemove() => SelectedNode != null;

        [RelayCommand]
        private async Task ShowAddProjectDialog()
        {
            await Task.CompletedTask;
            AddP = true;
        }

        [RelayCommand(CanExecute = nameof(CanAddGame))]
        private async Task ShowAddGameDialog()
        {
            await Task.CompletedTask;
            AddG = true;
        }

        [RelayCommand]
        private async Task ConfirmAddProject()
        {
            if (string.IsNullOrWhiteSpace(NewProjectName)) return;
            var res = await _service.AddNewPAsync(NewProjectName);
            if (res.Data)
                await LoadData();
            else
                GlobalMessage.Instance.ShowError(JSON.Serialize(res.Errors));
            AddP = false;
        }

        [RelayCommand]
        private async Task ConfirmAddGameAsync()
        {
            if (SelectedNode == null || string.IsNullOrWhiteSpace(NewGameName)) return;
            var res = await _service.AddNewGAsync(SelectedNode.Id, NewGameName);
            if (res.Data)
                await LoadData();
            else
                GlobalMessage.Instance.ShowError(JSON.Serialize(res.Errors));

            AddG = false;
        }

        [RelayCommand]
        private async Task ConfirmDelAsync()
        {
            if (SelectedNode == null) return;
            if (SelectedNode.Parent == null)
            {
                var view = new MsgViewDialogView("警告", 3002, "您确认要删除项目", SelectedNode.Name, "的数据吗？");
                var resxx = await ExtentHelper.GetService<IDialogService>().ShowDialog(view);
                if (!(bool)resxx)
                    return;
                // 如果是根节点

                var rrs = await _service.DelPAsync(SelectedNode.Id);
                Nodes.Remove(SelectedNode);
            }
            else
            {
                // 如果是子节点
                var view = new MsgViewDialogView("警告", 3002, "您确认要删除大区", SelectedNode.Name, "的数据吗？");
                var resxx = await ExtentHelper.GetService<IDialogService>().ShowDialog(view);
                if (!(bool)resxx)
                    return;
                var rresa = await _service.DelGAsync(SelectedNode.Id);
                SelectedNode.Parent.Children.Remove(SelectedNode);
            }

            SelectedNode = null;
            await LoadData();
            DelTN = false;
        }

        [RelayCommand]
        private void CancelAddProject() => AddP = false;

        [RelayCommand]
        private void CancelAddGame() => AddG = false;

        [RelayCommand]
        private void CancelDel() => DelTN = false;

        private async Task LoadData()
        {
            IsLoading = true;
            try
            {
                var res = await _service.GetAllAsync();
                if (res.Data.IsNullOrEmpty())
                    return;
                Nodes.Clear();
                foreach (var data in res.Data)
                {
                    var p = new TreeNode() { IsParent = true, Id = data.Id, Name = data.Name, Type = 0 };
                    Nodes.Add(p);
                    foreach (var game in data.Games)
                        p.Children.Add(new() { IsParent = false, Parent = p, Type = 1, Id = game.Id, Name = game.Name, Status = (int)game.Status });
                }
            }
            catch (Exception ex)
            {
                GlobalMessage.Instance.ShowError($"数据加载错误：{ex.Message}");
            }
            finally
            {
                IsLoading = false;
            }
        }
    }
}